package com.qf.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import static com.alipay.api.AlipayConstants.*;

/**
 * @author xingyu
 */

@RestController
@RequestMapping("/zhifu")
@Api(description = "支付")
public class PayController {

    private static final String privateKey = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCavqEjfPbdHoXbThQYQ+DsX2175KmJY1YqvbH+WVC+9Afx4a4nbGKqtFdpsZO+Co22jGsWSVOGRazsSMF8PwnVNu3egdeTapFJ34LlLm5aB0NVl4aXnuTOb5L8H8Y1Qbzca+GbUjtaz8HROhPEG3lnidsXx3nerUI8JdRhItIVT9gRoZNR03iO/+waAOvHozPu9IV8gsyGibQn+Cb3FiJ6Rtre3T4XGQ2zLMo5sxYYcZKTTtrW/21JPQaMDB93To5qwaN7/lWdX4t+Wa73l4Xr+q10niTz4/Ec78ISe1j4i6vpuDdfcVHWHDOr/iKGhZYKmjVy55OuvIsp/TN8eM3nAgMBAAECggEAXM+XABz0Rz0GVblnrgIQRlUZ6mQEFyXgSXRK7F2PY2gj17xe4sBMEUxm3TqnfSUBSArCM7S5BuCFTZZ5jdaVRC9Uzc6ciIszJtaKwIBvqUmP5icij4+6deJPiy5XiBusdZuyzaCtftL60U1/C3DbCPGS2ZlHi/norwCVd8kVrbesIgecVi51K82x69YK6muKr7w9cNaTOXpV2vzfizOagLXT8OcNwtCxd5uo6JMn5mDeY4GnOAzI41cYh79pTd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sgyWagcdVJ9Wvav+uydSocsdQWLA4n/Vj8LUz0IfqRYMb/KxMqstiDUmg4lVeq1UooA5vDwVIR4wGBddcMafe/+WU0wmhVeVi+LtRD6Da5MhAWwdMrWsFOBapeh+c4UgOlOBP/JAr5XYuiwdXXO4dokjDVimNujQjvhY/czscgmsRuPwsQdRlaX7U97kjt0rIDiErRBsUHWn0Ft1DVNSJh8Kv8nCgkLq65fOQADgMjUsnJ7E8ECi1rbIe8JrS+X/I4vKLbwjzhQrDsMTzS8pxX6BaqZsoQIDAQAB";


    @RequestMapping("/pay")
    public void pay(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws ServletException, IOException {
        {

//1:生成请求支付客户端
            AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipaydev.com/gateway.do", "2021000121673476", privateKey, "json", "utf-8", publiceKey, "RSA2");  //获得初始化的AlipayClient
//2:声明交易方式,网页端支付
            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest(); //创建API对应的request
//3:支付宝同步返回的页面
            alipayRequest.setReturnUrl("http://localhost:8080/#/success");
//4支付宝异步通知
            alipayRequest.setNotifyUrl(" http://mgprqg.natappfree.cc/zhifu//notifyUrl"); //在公共参数中设置回跳和通知地址
//5设置支付的参数
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("out_trade_no", UUID.randomUUID().toString());
            jsonObject.put("product_code", "FAST_INSTANT_TRADE_PAY");
            jsonObject.put("total_amount", "1000");
            jsonObject.put("subject", "包子");
            jsonObject.put("body", "包子是金子做的");

            alipayRequest.setBizContent(
                    jsonObject.toJSONString()
//                "{"  +
////订单号唯一
//                "    \"out_trade_no\":\"20150320010101001\","  +
////固定写法
//                "    \"product_code\":\"FAST_INSTANT_TRADE_PAY\","  +
////价格
//                "    \"total_amount\":88.88,"  +
////主题
//                "    \"subject\":\"Iphone6 16G\","  +
////内容
//                "    \"body\":\"Iphone6 16G\","  +
//
//                "    \"passback_params\":\"merchantBizType%3d3C%26merchantBizNo%3d2016010101111\","  +
//
//                "    \"extend_params\":{"  +
//
//                "    \"sys_service_provider_id\":\"2088511833207846\""  +
//
//                "    }" +
//
//                "  }"

            ); //填充业务参数
            String form = "";

            try {
//请求支付宝获取支付表单 form
                form = alipayClient.pageExecute(alipayRequest).getBody();  //调用SDK生成表单

            } catch (AlipayApiException e) {

                e.printStackTrace();

            }

            httpResponse.setContentType("text/html;charset=utf-8");

            httpResponse.getWriter().write(form); //直接将完整的表单html输出到页面

            httpResponse.getWriter().flush();

            httpResponse.getWriter().close();

        }


    }


    @RequestMapping("/notifyUrl")
    public void notfiyUrl(HttpServletRequest request) throws AlipayApiException {
        //将异步通知中收到的所有参数都存放到map中 将Request请求中的参数重组为map集合
        Map<String, String> paramsMap = convertRequestParamsToMap(request);

        boolean signVerified = AlipaySignature.rsaCheckV1(paramsMap, publiceKey, "utf-8", "RSA2"); //调用SDK验证签名
        if(signVerified){
            // TODO 验签成功后，按照支付结果异步通知中的描述，对支付结果中的业务内容进行二次校验，校验成功后在response中返回success并继续商户自身业务处理，校验失败返回failure
            System.out.println("验签成功！！！");
            System.out.println("当前回调的订单编号为:"+paramsMap.get("out_trade_no"));
            System.out.println("当前回调的appid为:"+paramsMap.get("app_id"));
            System.out.println("当前订单支付的金额为:"+paramsMap.get("total_amount"));
            System.out.println("当前订单状态为:"+paramsMap.get("trade_status"));
            //通过订单号更改数据库的该笔订单的交易状态

        }else{
            // TODO 验签失败则记录异常日志，并在response中返回failure.
        }
    }

    // 将request中的参数转换成Map
    private static Map<String, String> convertRequestParamsToMap(HttpServletRequest request) {
        Map<String, String> retMap = new HashMap<String, String>();

        Set<Map.Entry<String, String[]>> entrySet = request.getParameterMap().entrySet();

        for (Map.Entry<String, String[]> entry : entrySet) {
            String name = entry.getKey();
            String[] values = entry.getValue();
            int valLen = values.length;

            if (valLen == 1) {
                retMap.put(name, values[0]);
            } else if (valLen > 1) {
                StringBuilder sb = new StringBuilder();
                for (String val : values) {
                    sb.append(",").append(val);
                }
                retMap.put(name, sb.toString().substring(1));
            } else {
                retMap.put(name, "");
            }
        }

        return retMap;
    }

}
